package cn.wizzer.app.web.modules.controllers.platform.bus.equipment;

import cn.wizzer.app.bus.modules.models.equipment.BusEquipment;
import cn.wizzer.app.bus.modules.models.equipment.BusEquipmentProcess;
import cn.wizzer.app.bus.modules.models.equipment.BusEquipmentServicing;
import cn.wizzer.app.bus.modules.models.equipment.BusEquipmentStatus;
import cn.wizzer.app.bus.modules.services.BusEquipmentProcessService;
import cn.wizzer.app.bus.modules.services.BusEquipmentService;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysUnitService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.ShiroUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import cn.wizzer.app.bus.modules.services.BusEquipmentStatusService;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import java.sql.Connection;
import java.util.List;
import java.util.Map;

/**
 * @author tcjinxiu.com
 * @time 2024-04-11 10:19:44
 *
 */
@IocBean
@At("/platform/bus/equipment/status")
public class BusEquipmentStatusController {
private static final Log log = Logs.get();
	@Inject
	BusEquipmentStatusService busEquipmentStatusService;
	@Inject
	BusEquipmentService busEquipmentService;
	@Inject
	BusEquipmentProcessService busEquipmentProcessService;
	@Inject
	private SysDictService sysDictService;
	@Inject
	private SysUnitService sysUnitService;
	@Inject
	private SysUserService sysUserService;
	@Inject
	private ShiroUtil shiroUtil;

	private static final String type="status";
	//private static final int[] EquipmentStatus = {0,1,2,3,4,5,8,9};//停用启用流程"ask department chargeLeader finance leadership

	@At("/?")
	@Ok("beetl:/platform/bus/equipment/status/index.html")
	@RequiresAuthentication
	public void index(String processName,HttpServletRequest req) {
		req.setAttribute("userId",StringUtil.getPlatformUid());
		//String processCode = sysDictService.getProcessCode(processName);
		req.setAttribute("processName", processName);
		Map processMap =sysDictService.getCodeMap("equipmentProcessCode");
		req.setAttribute("processMap", JSONObject.fromObject(processMap));
		req.setAttribute("processOptions", JSONArray.fromObject(busEquipmentProcessService.listThisProcess(processMap, new int[]{0, 1, 2, 3, 4})));
		req.setAttribute("calculateMap", JSONObject.fromObject(sysDictService.getCodeMap("calculate")));
		req.setAttribute("calculateCycleTypeMap", JSONObject.fromObject(sysDictService.getCodeMap("calculateCycleType")));
		req.setAttribute("statusMap", JSONObject.fromObject(sysDictService.getCodeMap("equipmentStatus")));

	}

	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object data(@Param("code") String code, @Param("name") String name,@Param("lczt") String lczt,
					   @Param("equipmentStatus") String equipmentStatus,
					   @Param("processName") String processName,
					   @Param("pageNumber") int pageNumber,@Param("pageSize") int pageSize
			, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
		try {
			String sql = "select e.code,e.name,e.model,ur.username as managerName,ut.name as applyName,urr.username as opName," +
					" es.id,es.lczt,es.nextspr,es.equipmentStatus,es.statusTime,es.explains,FROM_UNIXTIME(es.opAt) as opTime,es.opBy " +
					" from bus_equipment_status es  " +
					" left join bus_equipment e on es.equipmentId=e.id " +
					" left join sys_user ur on ur.id=e.managerBy " +
					" left join sys_unit ut on ut.id = e.applyDept " +
					 "left join sys_user urr on urr.id=es.opBy "+
					" where es.delFlag=0 ";
			if(StringUtils.isNotBlank(processName)&& processName.equals("audit")){
				sql+= " and es.nextsprIds='"+StringUtil.getPlatformUid()+"' and (es.lczt = 2 or es.lczt = 1)";
			}else{
				//数据权限
				sql+= StringUtil.dataScopeFilter("es");
			}
			if(StringUtils.isNotBlank(code)){
				sql+= " and  e.code like '%"+code+"%' ";
			}
			if(StringUtils.isNotBlank(name)){
				sql+= " and  e.name like '%"+name+"%' ";
			}
			if(StringUtils.isNotBlank(lczt)){
				sql+= " and  es.lczt = '"+lczt+"' ";
			}
			if(StringUtils.isNotBlank(equipmentStatus)){
				sql+= " and  es.equipmentStatus ='"+equipmentStatus+"' ";
			}
			sql="select * from ("+sql+") a";
			if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
				if ("ascending".equalsIgnoreCase(pageOrderBy)) {
					sql+= " order by "+pageOrderName+" asc,opTime desc ";
				} else {
					sql+= " order by "+pageOrderName+" desc,opTime desc ";
				}
			}else{
				sql+= " order by opTime desc ";
			}
			return Result.success().addData(busEquipmentStatusService.listPage(pageNumber, pageSize, Sqls.create(sql)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error();
		}
	}

	@Aop(TransAop.READ_COMMITTED)
	@At
	@Ok("json")
	@RequiresPermissions("equipment.status.add")
	@SLog(tag = "Add", msg = "Add:bus_equipment_status")
	public Object addDo(@Param("..") BusEquipmentStatus status, HttpServletRequest req) {
		try {
			status = busEquipmentStatusService.insert(status);
			BusEquipmentProcess process = new BusEquipmentProcess();
			process.setHeadId(status.getId());
			process.setEquipmentId(status.getEquipmentId());
			process.setLczt(status.getLczt());
			process.setType(type);
			process.setStatus("0");
			process.setNextspr(status.getNextspr());
			process.setNextsprIds(status.getNextsprIds());
			busEquipmentProcessService.insert(process);
			busEquipmentStatusService.clearCache();
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@At("/detail/?")
	@Ok("json")
	@RequiresAuthentication
	public Object detail(String id) {
		BusEquipmentStatus status = busEquipmentStatusService.fetch(id);
		List listProcess = busEquipmentProcessService.list(Sqls.create("select *,(select username from sys_user where id = es.opBy) as opName,FROM_UNIXTIME(es.opAt) as opTime from  bus_equipment_process es where " +
				" equipmentId='"+status.getEquipmentId()+"' and headId='"+status.getId()+"' and type='"+type+"' order by opAt desc"));
		NutMap map = new NutMap();
		map.addv("status", status);
		//map.addv("equipment", equipment);
		map.addv("listProcess", listProcess);
		try {
			return Result.success("system.success").addData(map);
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@Aop(TransAop.READ_COMMITTED)
	@At
	@Ok("json")
	@RequiresPermissions("equipment.status.edit")
	@SLog(tag = "Edit", msg = "Edit:bus_equipment_status")
	public Object editDo(@Param("..") BusEquipmentStatus status, HttpServletRequest req) {
		try {
			BusEquipmentProcess process = new BusEquipmentProcess();
			process.setHeadId(status.getId());
			process.setEquipmentId(status.getEquipmentId());
			process.setLczt(status.getLczt());
			process.setType(type);
			process.setStatus("0");
			process.setOpBy(StringUtil.getPlatformUid());
			process.setOpAt(Times.getTS());
			process.setNextspr(status.getNextspr());
			process.setNextsprIds(status.getNextsprIds());
			//busEquipmentService.update(equipment);
			busEquipmentStatusService.update(status);
			busEquipmentProcessService.execute(Sqls.create("update bus_equipment_process set delflag=1 where lczt>=" + status.getLczt() + " and headId='" + status.getId() + "' and type='" + type + "' "));
			busEquipmentProcessService.insert(process);
			busEquipmentStatusService.clearCache();
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@Aop(TransAop.READ_COMMITTED)
	@At("/subDo/?")
	@Ok("json")
	@RequiresPermissions("equipment.status.edit")
	@SLog(tag = "subDo", msg = "subDo:bus_equipment_servicing")
	public Object subDo(String id) {
		try {
			BusEquipmentStatus status = busEquipmentStatusService.fetch(id);
			status.setLczt("1");
			BusEquipmentProcess process = busEquipmentProcessService.fetch(Cnd.NEW().and("headId", "=", status.getId())
					.and("lczt","=","0").and("delflag","=","0").and("type", "=", type));
			process.setHeadId(status.getId());
			process.setEquipmentId(status.getEquipmentId());
			process.setLczt(status.getLczt());
			process.setType(type);
			process.setStatus("0");
			process.setOpBy(StringUtil.getPlatformUid());
			process.setOpAt(Times.getTS());
			//busEquipmentService.update(equipment);
			busEquipmentStatusService.update(status);
			busEquipmentProcessService.execute(Sqls.create("update bus_equipment_process set delflag=1 where lczt>=" + status.getLczt() + " and headId='" + status.getId() + "' and type='" + type + "' "));
			busEquipmentProcessService.insert(process);
			busEquipmentStatusService.clearCache();
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@At
	@Ok("json")
	@RequiresAuthentication
	@SLog(tag = "processDo", msg = "processDo:bus_equipment_status")
	public Object processDo(@Param("..") BusEquipmentStatus status,@Param("..") BusEquipmentProcess process,
							HttpServletRequest req) {
		try {
			BusEquipment equipment = busEquipmentService.fetch(status.getEquipmentId());
			if (status.getAuditFlag().equals("0")) {
				status.setLczt("2");
			} else if (process.getStatus().equals("0")) {
				status.setLczt("4");
				status.setNextspr(null);
				status.setNextsprIds(null);
				process.setNextspr(null);
				process.setNextsprIds(null);
				//最后一级审批通过则进入停用、启用状态
				equipment.setStatus(status.getEquipmentStatus());
			} else {
				status.setLczt("3");
				status.setNextspr(null);
				status.setNextsprIds(null);
				process.setNextspr(null);
				process.setNextsprIds(null);
			}
			process.setHeadId(status.getId());
			process.setEquipmentId(status.getEquipmentId());
			process.setLczt(status.getLczt());
			process.setType(type);
			process.setOpBy(StringUtil.getPlatformUid());
			process.setOpAt(Times.getTS());
			busEquipmentService.update(equipment);
			busEquipmentStatusService.update(status);
			busEquipmentProcessService.insert(process);
			busEquipmentStatusService.clearCache();
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@At({"/delete","/delete/?"})
	@Ok("json")
	@RequiresPermissions("equipment.status.delete")
	@SLog(tag = "Delete", msg = "Delete:bus_equipment_status")
	public Object delete(String id,@Param("ids") String[] ids, HttpServletRequest req) {
		try {
			if(ids!=null&&ids.length>0){
				busEquipmentStatusService.vDelete(ids);
			}else{
				busEquipmentStatusService.vDelete(id);
			}
			busEquipmentStatusService.clearCache();
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
}
